﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using JMT.Data;
using JMT.Data.Events;

namespace JMT.Controls.Views
{
    /// <summary>
    /// JTreeView.xaml 的交互逻辑
    /// </summary>
    public partial class JTreeView : UserControl, IEventHandler
    {
        public JTreeView()
        {
            InitializeComponent();
        }

        public void Bind(JSolution jSolution)
        {
            this._ctlTreeView.Items.Clear();

            TreeViewItem item = new JTreeNode(jSolution);

            BindNodes(item, jSolution);

            this._ctlTreeView.Items.Add(item);
            item.IsExpanded = true;
        }

        private void BindNodes(TreeViewItem tidl, IJContainer jContainer)
        {
            List<JModel> children = jContainer.ToList();
            foreach (var jModel in children)
            {
                if (!(jModel is JRelation) && !(jModel is JElement))
                {
                    JTreeNode jTreeNode = new JTreeNode(jModel);
                    tidl.Items.Add(jTreeNode);
                    if (jModel is IJContainer)
                    {
                        BindNodes(jTreeNode, jModel as IJContainer);
                    }
                }
            }
        }

        public void Handle(EventBase @event)
        {
            if (@event is AddModelEvent)
            {
                AddModelEvent addEvent = @event as AddModelEvent;
                IJContainer jContainer = addEvent.JContainer;
                JModel jModel = addEvent.JModel;

                if (!(jModel is JRelation) && !(jModel is JElement))
                {
                    TreeViewItem pItemNode = this._ctlTreeView.GetNode(jContainer as JModel);

                    List<JModel> children = jContainer.ToList();
                    for (int index = 0; index < children.Count; index++)
                    {
                        if (children[index] == jModel)
                        {
                            TreeViewItem itemNode = new JTreeNode(jModel);
                            pItemNode.Items.Insert(index, itemNode);
                            break;
                        }
                    }
                    pItemNode.IsExpanded = true;
                }
            }
        }
    }
}
